package com.yizhe.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.yizhe.controller.Constants;


/**
 * @author Jiang,JiaYong
 * @version 2014-03-18
 * @desc 管理后台判断是否登录拦截器
 */
public class ManagerInterceptor extends HandlerInterceptorAdapter {
	protected final Logger logger = LoggerFactory.getLogger(super.getClass());

	/**
	 * 拦截到没有登录的时候调整地址
	 */
	private String loginPage;

	/**
	 * 包含什么字符串排除【多个以英文逗号分隔】
	 */
	private String exclude_indexof;

	/**
	 * 拦截处理，返回true继续往下走，返回false终止继续请求。obj 参数指在拦截器链上的下一个连接器，如果没有了则是controller
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
		// logger.info("--------------- Start processing session intercept -------------");
		String requestPath = request.getServletPath();
		if(-1 != StringUtils.indexOf(requestPath, this.getExclude_indexof())){
			return true;
		}
		
		Object session_user_info = request.getSession().getAttribute(Constants.USER_INFO);
		if (null == session_user_info || "".equals(session_user_info.toString())) {
			response.sendRedirect(this.getCtxPath(request) + this.loginPage);
			return false;
		}
		return true;
	}

	public String getCtxPath(HttpServletRequest request) {
		StringBuffer ctx = new StringBuffer();
		ctx.append(request.getScheme()).append("://").append(request.getServerName()).append(":").append(request.getServerPort());
		ctx.append(request.getContextPath());
		return ctx.toString();
	}

	public String getLoginPage() {
		return loginPage;
	}

	public void setLoginPage(String loginPage) {
		this.loginPage = loginPage;
	}

	public String getExclude_indexof() {
		return exclude_indexof;
	}

	public void setExclude_indexof(String exclude_indexof) {
		this.exclude_indexof = exclude_indexof;
	}

}
